package com.kun.lagou.user.starter.annotation;

import com.alibaba.fastjson.JSONObject;
import com.kun.lagou.user.starter.vo.UserVo;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.impl.DefaultClaims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

import static com.kun.lagou.user.starter.constant.Constant.COOKIE_NAME;
import static com.kun.lagou.user.starter.constant.Constant.SECRETKEY;

/**
 * @author Administrator
 */
@Slf4j
@Component
public class LoginUserIdResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private HttpServletRequest request;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(LoginUserId.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Jwt jwt = Jwts.parser().setSigningKey(SECRETKEY)
                .parseClaimsJws(Arrays.stream(request.getCookies())
                .filter(c -> COOKIE_NAME.equals(c.getName()))
                        .findFirst().get().getValue());
        //TODO 如果校验失败，返回401，或者自定义的异常数据
        log.info("jwt body {}", jwt.getBody());
        return JSONObject.parseObject((((DefaultClaims)jwt.getBody()).getSubject()), UserVo.class);
    }
}
